<?php


namespace app\model;

use think\Model;

class AdminRoleMenu extends Model
{
    public $roleId;
    public $menuId;

    private $adminMenu;
    private $data;

    public function __construct(array $data = [])
    {
        parent::__construct($data);
        $this->adminMenu = new AdminMenu();
        $this->data = array();
    }

    public function __destruct()
    {
        parent::__destruct();
        unset(
            $this->adminMenu,
            $this->data
        );
    }

    public function getMenuPermission()
    {
        return $this->where('role_id', $this->roleId)
            ->field('role_id, menu_id')
            ->select()->each(
                function ($item)
                {
                    if ($item['menu_id'] == 0)
                    {
                        $item['menu_list'] = $this->adminMenu->queryTop();
                    }else{
                        $this->adminMenu->menuId = $item['menu_id'];
                        $item['menu_list'] = $this->adminMenu->queryMenu();
                    }
                }
            )->toArray();
    }

    public function getSignInUserMenuPermisson()
    {
        $roleList = explode('|', $this->roleId);
        foreach ($roleList as $value)
        {
            $data = $this->where('role_id', $value)
                ->field('role_id, menu_id')
                ->find()->toArray();
            if ($data['menu_id'] == 0)
            {
                $data['menu_list'] = $this->adminMenu->read();
            }else{
                $this->adminMenu->menuId = $data['menu_id'];
                $data['menu_list'] = $this->adminMenu->getSignInUsersMenuData();
            }
            $this->data[] = $data;
        }
        return $this->data;
    }

    public function addAdminRoleMenu()
    {
        $this->data['role_id'] = $this->roleId;
        $this->data['menu_id'] = $this->menuId;
        return $this->save($this->data);
    }

    public function editAdminRoleMenu()
    {
        $this->data['menu_id'] = $this->menuId;
        return $this->where('role_id', $this->roleId)
            ->save($this->data);
    }
}